package com.chauncy.DMS.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import util.List2Json1.List2Json1;

import com.chauncy.DMS.dao.ManagerDaoImplement;

public class SelectDormServlet extends HttpServlet {

	private static ManagerDaoImplement daoImplement = new ManagerDaoImplement();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String flag = request.getParameter("flag");
		String buildName = request.getParameter("buildName");
		
		//根据性别找楼栋
		if(flag.equals("sex")){
			int stuSex = Integer.parseInt(String.valueOf( request.getParameter("stuSex")));
			 List<Map<String,Object>> buildList= getBuildBySex(stuSex);
			 JSONArray buildObject = JSONArray.fromObject(buildList);
			 response.getWriter().print(buildObject);
		}
		//根据楼栋 楼层 找宿舍
		if(flag.equals("buildName")){
			int floor = Integer.valueOf(String.valueOf(request.getParameter("floor")));
			 List<Map<String,Object>> buildList = getDormByBuildAndFloor(buildName,floor);
			 JSONArray dormObject = JSONArray.fromObject(buildList);
			 response.getWriter().print(dormObject);
		}
		
		//提交宿舍
		if(flag.equals("selectDorm")){
			JSONObject object = JSONObject.fromObject(request.getParameter("dormInfo"));
			int submitResult = submitDorm(object);
			response.getWriter().print(submitResult);
		}
	}
	
	//通过性别查楼栋
	private static List<Map<String,Object>> getBuildBySex(int sex){
		String sql = "SELECT Buildings_number" +
				" FROM building_info_table where Buildings_type = ?;";
		Object[] param = {sex};
		return daoImplement.query(sql,param);
	}
	//通过楼栋 楼层 查询宿舍
	private static List<Map<String, Object>> getDormByBuildAndFloor(String build,int floor){
		String sql = "select Dorm_number from dorm_info_table" +
				" WHERE  (Checkin_number - Actual_number_of_people) > 0" +
				" AND Buildings_number = ? and Floor_number = ?;";
		Object[] param = {build,floor};
		return daoImplement.query(sql,param);
	}
	//提交选择的宿舍信息
	private static int submitDorm(JSONObject object){
		System.out.println(object);
		String sql = "insert into stu_dorm_info_table (Stu_name," +
				"Stu_number,Stu_sex,College,Study_major,The_Class," +
				"Telephone,Dormitory_number,Dorm_number," +
				"Checkin_time) VALUES (?,?,?,?,?,?,?,?,?,NOW());";
		Object[] param = {object.get("Stu_name"),object.get("Stu_number"),
		Integer.parseInt(String.valueOf(object.get("Stu_sex"))),object.get("College"),
		object.get("Study_major"),object.get("The_class"),object.get("Telephone"),
		object.get("buildingsList"),object.get("dormList")};
		return daoImplement.updata(sql, param);
	}
}
